'use strict'

const semver = require('semver')
const colors = require('colors')
const log = require('@zy-cli/log')
const { getType } = require('@zy-cli/utils')

const LOWEST_NODE_VERSION = '12.0.0'

class Command {
    constructor(argv) {
        if (!argv) {
            throw new Error('参数不能为空！')
        }
        if (!Array.isArray(argv)) {
            throw new Error(`期望参数类型为Array，但传入的是：${getType(argv)}`)
        }
        if (!argv.length) {
            throw new Error('参数列表为空！')
        }
        this._argv = argv
        const runner = new Promise((resolve, reject) => {
            let chain = Promise.resolve()
            chain = chain.then(() => this.checkNodeVersion())
            chain = chain.then(() => this.initArgs())
            chain = chain.then(() => this.init())
            chain = chain.then(() => this.exec())
            chain.catch(err => {
                log.error(err.message)
            })
        })
    }

    init() {
        throw new Error('子类需要实现init方法！')
    }

    exec() {
        throw new Error('子类需要实现exec方法！')
    }

    initArgs () {
        this._cmd = this._argv[this._argv.length - 1]
        this._argv = this._argv.slice(0, this._argv.length - 1)
    }

    // 检查 node 版本
    checkNodeVersion() {
        // 获取当前 node 版本号
        const currentVersion = process.version
        // 最低版本号
        const lowestVersion = LOWEST_NODE_VERSION
        // 比对
        if (!semver.gte(currentVersion, lowestVersion)) {
            throw new Error(colors.red(`zy-cli 需要安装 v${lowestVersion} 以上版本的 Node.js`))
        }
    }
}
 
module.exports = Command
